import React, { useState } from 'react';
import { Mail, Send, TestTube, Save, Shield, Server } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

const EmailConfig = ({ toggleSidebar }) => {
  const [config, setConfig] = useState({
    provider: 'smtp',
    smtpHost: 'smtp.example.com',
    smtpPort: '587',
    smtpUser: '',
    smtpPassword: '',
    smtpSecurity: 'tls',
    fromEmail: '',
    fromName: '',
    replyTo: '',
    enableAuth: true,
    enableSSL: false,
    timeout: 30
  });

  const [testEmail, setTestEmail] = useState('');
  const [testResult, setTestResult] = useState(null);
  const [isTesting, setIsTesting] = useState(false);

  const handleConfigChange = (key, value) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  const handleSaveConfig = () => {
    console.log('保存邮件配置', config);
    // 这里实现保存逻辑
  };

  const handleTestEmail = async () => {
    if (!testEmail) return;
    
    setIsTesting(true);
    
    // 模拟测试邮件发送
    setTimeout(() => {
      setTestResult({
        success: true,
        message: '测试邮件发送成功！',
        details: `邮件已发送到 ${testEmail}`
      });
      setIsTesting(false);
    }, 2000);
  };

  const emailProviders = [
    { value: 'smtp', label: 'SMTP服务器' },
    { value: 'gmail', label: 'Gmail' },
    { value: 'outlook', label: 'Outlook' },
    { value: 'qq', label: 'QQ邮箱' },
    { value: '163', label: '163邮箱' },
    { value: 'aliyun', label: '阿里云邮件' }
  ];

  const securityOptions = [
    { value: 'none', label: '无加密' },
    { value: 'tls', label: 'TLS' },
    { value: 'ssl', label: 'SSL' }
  ];

  const getProviderDefaults = (provider) => {
    const defaults = {
      gmail: { host: 'smtp.gmail.com', port: '587', security: 'tls' },
      outlook: { host: 'smtp-mail.outlook.com', port: '587', security: 'tls' },
      qq: { host: 'smtp.qq.com', port: '587', security: 'tls' },
      '163': { host: 'smtp.163.com', port: '994', security: 'ssl' },
      aliyun: { host: 'smtpdm.aliyun.com', port: '80', security: 'none' }
    };
    return defaults[provider] || { host: '', port: '587', security: 'tls' };
  };

  const handleProviderChange = (provider) => {
    const defaults = getProviderDefaults(provider);
    setConfig(prev => ({
      ...prev,
      provider,
      smtpHost: defaults.host,
      smtpPort: defaults.port,
      smtpSecurity: defaults.security
    }));
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Mail className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    邮件配置
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    配置系统邮件发送服务
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" onClick={handleTestEmail} disabled={isTesting}>
                {isTesting ? (
                  <>
                    <div className="w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin" />
                    测试中
                  </>
                ) : (
                  <>
                    <TestTube className="w-4 h-4 mr-2" />
                    测试邮件
                  </>
                )}
              </Button>

              <Button onClick={handleSaveConfig}>
                <Save className="w-4 h-4 mr-2" />
                保存配置
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 左侧：配置表单 */}
          <div className="lg:col-span-2 space-y-6">
            <Card>
              <CardContent className="p-6">
                <Tabs defaultValue="basic" className="w-full">
                  <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="basic">基础配置</TabsTrigger>
                    <TabsTrigger value="advanced">高级设置</TabsTrigger>
                    <TabsTrigger value="templates">邮件模板</TabsTrigger>
                  </TabsList>

                  <TabsContent value="basic" className="mt-6 space-y-6">
                    {/* 邮件服务商 */}
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold text-material-grey-800">
                        邮件服务商
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <Label htmlFor="provider">服务商类型</Label>
                          <Select value={config.provider} onValueChange={handleProviderChange}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {emailProviders.map(provider => (
                                <SelectItem key={provider.value} value={provider.value}>
                                  {provider.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    </div>

                    {/* SMTP配置 */}
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold text-material-grey-800">
                        SMTP服务器配置
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <Label htmlFor="smtp-host">SMTP主机</Label>
                          <Input
                            id="smtp-host"
                            value={config.smtpHost}
                            onChange={(e) => handleConfigChange('smtpHost', e.target.value)}
                            placeholder="smtp.example.com"
                          />
                        </div>
                        <div>
                          <Label htmlFor="smtp-port">端口</Label>
                          <Input
                            id="smtp-port"
                            value={config.smtpPort}
                            onChange={(e) => handleConfigChange('smtpPort', e.target.value)}
                            placeholder="587"
                          />
                        </div>
                        <div>
                          <Label htmlFor="smtp-user">用户名</Label>
                          <Input
                            id="smtp-user"
                            value={config.smtpUser}
                            onChange={(e) => handleConfigChange('smtpUser', e.target.value)}
                            placeholder="your-email@example.com"
                          />
                        </div>
                        <div>
                          <Label htmlFor="smtp-password">密码</Label>
                          <Input
                            id="smtp-password"
                            type="password"
                            value={config.smtpPassword}
                            onChange={(e) => handleConfigChange('smtpPassword', e.target.value)}
                            placeholder="邮箱密码或授权码"
                          />
                        </div>
                      </div>
                    </div>

                    {/* 发件人信息 */}
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold text-material-grey-800">
                        发件人信息
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <Label htmlFor="from-email">发件人邮箱</Label>
                          <Input
                            id="from-email"
                            value={config.fromEmail}
                            onChange={(e) => handleConfigChange('fromEmail', e.target.value)}
                            placeholder="noreply@example.com"
                          />
                        </div>
                        <div>
                          <Label htmlFor="from-name">发件人名称</Label>
                          <Input
                            id="from-name"
                            value={config.fromName}
                            onChange={(e) => handleConfigChange('fromName', e.target.value)}
                            placeholder="系统通知"
                          />
                        </div>
                        <div className="md:col-span-2">
                          <Label htmlFor="reply-to">回复邮箱</Label>
                          <Input
                            id="reply-to"
                            value={config.replyTo}
                            onChange={(e) => handleConfigChange('replyTo', e.target.value)}
                            placeholder="support@example.com"
                          />
                        </div>
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="advanced" className="mt-6 space-y-6">
                    {/* 安全设置 */}
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold text-material-grey-800">
                        安全设置
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <Label htmlFor="security">加密方式</Label>
                          <Select value={config.smtpSecurity} onValueChange={(value) => handleConfigChange('smtpSecurity', value)}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {securityOptions.map(option => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Label htmlFor="timeout">超时时间(秒)</Label>
                          <Input
                            id="timeout"
                            type="number"
                            value={config.timeout}
                            onChange={(e) => handleConfigChange('timeout', parseInt(e.target.value))}
                            placeholder="30"
                          />
                        </div>
                      </div>
                      
                      <div className="space-y-3">
                        <div className="flex items-center space-x-2">
                          <Switch
                            id="enable-auth"
                            checked={config.enableAuth}
                            onCheckedChange={(checked) => handleConfigChange('enableAuth', checked)}
                          />
                          <Label htmlFor="enable-auth">启用SMTP认证</Label>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Switch
                            id="enable-ssl"
                            checked={config.enableSSL}
                            onCheckedChange={(checked) => handleConfigChange('enableSSL', checked)}
                          />
                          <Label htmlFor="enable-ssl">强制SSL连接</Label>
                        </div>
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="templates" className="mt-6 space-y-6">
                    {/* 邮件模板 */}
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold text-material-grey-800">
                        邮件模板配置
                      </h3>
                      <p className="text-sm text-material-grey-600">
                        配置系统邮件的默认模板和样式
                      </p>
                      
                      <div className="space-y-4">
                        <div>
                          <Label htmlFor="email-header">邮件头部</Label>
                          <Textarea
                            id="email-header"
                            rows={3}
                            placeholder="邮件头部HTML内容"
                          />
                        </div>
                        <div>
                          <Label htmlFor="email-footer">邮件底部</Label>
                          <Textarea
                            id="email-footer"
                            rows={3}
                            placeholder="邮件底部HTML内容"
                          />
                        </div>
                      </div>
                    </div>
                  </TabsContent>
                </Tabs>
              </CardContent>
            </Card>
          </div>

          {/* 右侧：测试和状态 */}
          <div className="lg:col-span-1 space-y-6">
            {/* 邮件测试 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Send className="w-5 h-5" />
                  <span>邮件测试</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="test-email">测试邮箱</Label>
                  <Input
                    id="test-email"
                    type="email"
                    value={testEmail}
                    onChange={(e) => setTestEmail(e.target.value)}
                    placeholder="test@example.com"
                  />
                </div>
                
                <Button 
                  onClick={handleTestEmail} 
                  disabled={!testEmail || isTesting}
                  className="w-full"
                >
                  {isTesting ? (
                    <>
                      <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      发送中...
                    </>
                  ) : (
                    <>
                      <Send className="w-4 h-4 mr-2" />
                      发送测试邮件
                    </>
                  )}
                </Button>

                {testResult && (
                  <div className={`p-3 rounded-lg ${
                    testResult.success 
                      ? 'bg-green-50 border border-green-200' 
                      : 'bg-red-50 border border-red-200'
                  }`}>
                    <div className={`font-medium text-sm ${
                      testResult.success ? 'text-green-800' : 'text-red-800'
                    }`}>
                      {testResult.message}
                    </div>
                    {testResult.details && (
                      <div className="text-xs text-material-grey-600 mt-1">
                        {testResult.details}
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 配置状态 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Server className="w-5 h-5" />
                  <span>配置状态</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">SMTP服务器</span>
                  <div className="flex items-center space-x-1">
                    <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                    <span className="text-xs text-green-600">已配置</span>
                  </div>
                </div>
                
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">认证信息</span>
                  <div className="flex items-center space-x-1">
                    <div className={`w-2 h-2 rounded-full ${
                      config.smtpUser && config.smtpPassword ? 'bg-green-500' : 'bg-yellow-500'
                    }`}></div>
                    <span className={`text-xs ${
                      config.smtpUser && config.smtpPassword ? 'text-green-600' : 'text-yellow-600'
                    }`}>
                      {config.smtpUser && config.smtpPassword ? '已配置' : '待配置'}
                    </span>
                  </div>
                </div>
                
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">发件人信息</span>
                  <div className="flex items-center space-x-1">
                    <div className={`w-2 h-2 rounded-full ${
                      config.fromEmail ? 'bg-green-500' : 'bg-red-500'
                    }`}></div>
                    <span className={`text-xs ${
                      config.fromEmail ? 'text-green-600' : 'text-red-600'
                    }`}>
                      {config.fromEmail ? '已配置' : '未配置'}
                    </span>
                  </div>
                </div>
                
                <div className="flex items-center justify-between">
                  <span className="text-sm text-material-grey-600">安全连接</span>
                  <div className="flex items-center space-x-1">
                    <Shield className="w-3 h-3 text-blue-600" />
                    <span className="text-xs text-blue-600">{config.smtpSecurity.toUpperCase()}</span>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 使用说明 */}
            <Card>
              <CardHeader>
                <CardTitle>使用说明</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm text-material-grey-600">
                <div>
                  <h4 className="font-medium text-material-grey-800 mb-1">Gmail配置</h4>
                  <p>需要开启两步验证并使用应用专用密码</p>
                </div>
                <div>
                  <h4 className="font-medium text-material-grey-800 mb-1">QQ邮箱配置</h4>
                  <p>需要开启SMTP服务并使用授权码</p>
                </div>
                <div>
                  <h4 className="font-medium text-material-grey-800 mb-1">企业邮箱</h4>
                  <p>请联系管理员获取SMTP服务器信息</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

export default EmailConfig;
